#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QAudioDeviceInfo>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QList<QAudioDeviceInfo> devices =QAudioDeviceInfo::availableDevices(QAudio::AudioInput);
    for (QAudioDeviceInfo device : devices) {
        ui->microphone->addItem(device.deviceName());
    }
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(qtimeSlot()));

}

MainWindow::~MainWindow()
{
    delete ui;
}

QString formatTime(int ms)
{
    int ss = 1;
    int mi = ss * 60;
    int hh = mi * 60;
    int dd = hh * 24;

    long day = ms / dd;
    long hour = (ms - day * dd) / hh;
    long minute = (ms - day * dd - hour * hh) / mi;
    long second = (ms - day * dd - hour * hh - minute * mi) / ss;
    long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

    QString hou = QString::number(hour,10);
    hou = hour < 10 ? "0" + hou : hou;
    QString min = QString::number(minute,10);
    min = minute < 10 ? "0" + min : min;
    QString sec = QString::number(second,10);
    sec = second < 10 ? "0" + sec : sec;
    QString msec = QString::number(milliSecond,10);

    //qDebug() << "minute:" << min << "second" << sec << "ms" << msec <<endl;

    return hou + ":" + min + ":" + sec ;
}

void MainWindow::on_start_clicked()
{
    timer->start(1000);
    pAudioRecorder = new AudioRecorder(this);
    ui->start->setEnabled(false);
    ui->stop->setEnabled(true);
    int muxType = ui->comboBox->currentIndex();
    qDebug()<< muxType ;
    mSeconds = 0;
    QVariantMap args;
    if(muxType == 1){
        args["filePath"] = "test3.aac";
    }
    else if(muxType == 2){
        args["filePath"] = "test3.mp3";
    }
    else { //默认mp4
        args["filePath"] = "test3.mp4";
    }
    args["audioBitrate"] = 128000;
    QString mic = ui->microphone->currentText();
    pAudioRecorder->Init(args);
    pAudioRecorder->setMicro(mic);

    pAudioRecorder->Start();



}

void MainWindow::qtimeSlot()
{
    mSeconds++;
    ui->time->setText(formatTime(mSeconds));
}


void MainWindow::on_stop_clicked()
{
    timer->stop();
    ui->stop->setEnabled(false);
    ui->start->setEnabled(true);

    if(pAudioRecorder){
        pAudioRecorder->Stop();
    }
}

